<?php
class Hydrum_Pathfinder_Paths implements Iterator
{
    /**
     * List of paths
     *
     * @var array
     */
    private $_paths = array();

    public function __construct(array $paths = array())
    {
        if ($paths) {
            $this->setPaths($paths);
        }
    }

    public function setPaths(array $paths)
    {
        foreach ($paths as $path) {

            $this->addPath($path);
        }

        return $this;
    }

    public function addPath($path)
    {
        if (file_exists($path)) {

            $this->_paths[] = $this->createPath($path);
        }

        return $this;
    }

    /**
     * Return list of containing paths
     *
     * @param boolean $reverse
     * @return array:
     */
    public function getPaths($reverse = false)
    {
        $paths = $this->_paths;

        if ($reverse) {

            $paths = array_reverse($paths);
        }

        return $paths;
    }

    /**
     * Create new path instance
     *
     * @param string $path
     * @return Hydrum_Pathfinder_Path
     */
    public function createPath($path)
    {
        $path = (string) $path;

        return new Hydrum_Pathfinder_Path($path);
    }

    /**
     * Merge paths with each other
     *
     * @param Hydrum_Pathfinder_Paths $paths
     */
    public function merge(Hydrum_Pathfinder_Paths $paths)
    {
        $basenames = array();

        foreach ($this->_paths as $i => $path) {

            $basenames[$i] = basename($path);
        }

        foreach ($paths as $path) {

            $basename = basename($path);

            $key = array_search($basename, $basenames);

            if ($key !== false) {
                $this->_paths[$key] = $path;
            } else {
                $this->_paths[] = $path;
            }
        }
    }

    public function first()
    {
        return $this->rewind();
    }

    public function rewind()
    {
        return reset($this->_paths);
    }

    public function current()
    {
        return current($this->_paths);
    }

    public function key()
    {
        return key($this->_paths);
    }

    public function next()
    {
        return next($this->_paths);
    }

    public function valid()
    {
        return key($this->_paths) !== null;
    }
    
    public function toArray()
    {
        return $this->_paths;        
    }
}
